import { Component, OnInit } from '@angular/core';
import { NzMessageService } from 'ng-zorro-antd/message';
import { FinanceOutDetailService } from './finance-out-detail.service';
import { PutSaveService } from '../../stock/put-save/put-save.service';
import { CommonService } from 'src/app/services-common/common.service';
import { PermissionService } from '../../../service/permission.service';
import { NzModalService } from 'ng-zorro-antd/modal';

@Component({
  selector: 'app-finance-out-detail',
  templateUrl: './finance-out-detail.component.html',
  styleUrls: ['./finance-out-detail.component.scss']
})
export class FinanceOutDetailComponent implements OnInit {
  isCollapse: boolean = false;

  // 状态集合
  stateSet: any = { 1: '草稿', 2: '已通知', 3: '已完成', 4: '已撤销' }
  // 出库类型(1、销售出库 2、直接出库  3、不良品返厂 4、坏件出库 5、代售出库)
  typeSet: any = {}

  queryForm: any = {
    // 出库类型(1、销售出库 2、直接出库  3、不良品返厂 4、坏件出库 5、代售出库)
    typeList: [],
    // 状态(1草稿 2已通知 3已完成 4已撤销)
    stateList: [],
    // 供应商
    supplierList: [],
    // 包含商品
    whGoods: '',
    // 实际出库开始日期
    beginTime: '',
    // 实际出库结束日期
    endTime: '',
    // 来源平台
    sourcePlatform: '',
    // 当前页
    page: 1,
    // 加载当前页数量 10
    pageSize: 20
  }
  // 临时缓存
  cacheData: any = {
    // 出库开始日期
    storageDate: []
  }

  // 列表数据
  tableData: any = {
    // list
    list: []
  }

  /**
   * 全局 loading
   */
  messageId: any = null;

  // 供应商列表
  supplierItems: any = [];

  exportLoading: boolean = false;

  // 订单来源
  orderSourceOptions: any = [];
  scurceSelected: any = [];

  constructor(
    private financeOutDetailService: FinanceOutDetailService,
    private putSaveService: PutSaveService,
    private message: NzMessageService,
    private commonService: CommonService,
    public permission: PermissionService,
    private modal: NzModalService
  ) { }

  async ngOnInit() {
    // 查询 订单来源平台
    this.orderSourceOptions = await this.commonService.getDictList('order_source_platform');
    this.htttpDict()
    this.httpList()
    // this.selectState()
    this.getSupplierData() // 供应商下拉
  }
  // 查询
  onQuery() {
    this.queryForm.page = 1
    this.httpList()
  }
  // 重置
  restQuery() {
    this.queryForm.typeList = [];
    this.queryForm.stateList = [];
    this.queryForm.supplierList = [];
    this.queryForm.whGoods = '';
    this.cacheData.storageDate = [];
    this.queryForm.beginTime = '';
    this.queryForm.endTime = '';
    this.queryForm.sourcePlatform = '';
    this.scurceSelected = [];

    this.queryForm.page = 1
    this.httpList()
  }

  // 选择日期时触发
  onStorageDateChange(val: any) {
    if (!val || val.length != 2) {
      this.queryForm.beginTime = ''
      this.queryForm.endTime = ''
      return
    }
    this.queryForm.beginTime = this.date(val[0])
    this.queryForm.endTime = this.date(val[1])
  }
  // 页码改变
  onPageIndexChange(index: Number) {
    this.queryForm.page = index;
    this.httpList()
  }
  // 每页条数改变的回调
  onPageSizeChange(index: Number) {
    this.queryForm.pageSize = index;
    this.httpList()
  }
  // 出库列表
  async httpList() {
    this.createBasicMessage()
    const { typeList, stateList } = this.queryForm
    const pramas = {
      ...this.queryForm
    }
    
    try {
      const { data }: any = await this.financeOutDetailService.findList(pramas)
      this.removeBasicMessage()
      this.tableData = data || { list: [] }

    } catch (error) {
      this.removeBasicMessage()
    }
  }
  // 出库类型
  async htttpDict() {
    try {
      const { data }: any = await this.putSaveService.dict('outbound_type')
      const { records } = data?.list
      records?.forEach((item: any) => {
        this.typeSet[item.content] = item.name
        // this.queryForm.type.push(item.content)
      });
    } catch (error) {

    }
  }

  // 获取下拉
  async getSupplierData() {
    try {
      let params = {
        page: 1,
        pageSize: '99999'
      }
      const res: any = await this.financeOutDetailService.getSupplierData(params);
      let tempArrs = res.data.records.filter((item: any) => {
        return !!item.name;
      })
      this.supplierItems = tempArrs || [];
    } catch {
      // console.log('error');
    }
  }

  // 导出请求
  onExport() {
    this.modal.confirm({
      nzTitle: '提示',
      nzContent: '即将导出符合本页面筛选条件的数据，为了导出速度请尽可能的控制时间范围。确认导出？',
      nzOkText: '确认',
      nzOkType: 'primary',
      nzOkDanger: true,
      nzOnOk: async () => {
        let params = {
          ...this.queryForm,
          page: 1,
          pageSize: 1000000
        }
        for (let key in params) {
          if (params[key] === null) {
            params[key] = '';
          }
    
          if (Array.isArray(params[key])) {
            params[key] = params[key].length ? params[key].join(',') : '';
          }
        }

        this.exportLoading = true;
        const res: any = await this.financeOutDetailService.export(params);
        this.exportLoading = false;

        if (res.type === 'application/octet-stream') {
          this.commonService.downLoadBlobFile(res, '出库明细');
        } else {
          this.message.error(res.message || '导出失败');
        }
      },
      nzCancelText: '取消'
    });
  }
  // 设置状态的默认值 全选
  selectState() {
    for (const key in this.stateSet) {
      this.queryForm.state.push(key)
    }
  }
  // table状态字段code转换成中文
  state_to_text(val: number) {
    return this.stateSet[val] || '-'
  }
  // table类型字段code转换成中文
  type_to_text(val: number) {
    return this.typeSet[val] || '-'
  }
  /**
    * 时间格式转换 年月日
    * @param date
    * @returns
    */
  date(date: any) {
    const d = new Date(date)
    return `${d.getFullYear()}-${this.p((d.getMonth() + 1))}-${this.p(d.getDate())}`;
  }
  /**
   * 补0
   * @param s
   */
  p(s: any) {
    return s < 10 ? '0' + s : s
  }
  /**
   * 开启loading
   */
  createBasicMessage(): void {
    this.messageId = this.message.loading('正在请求...', { nzDuration: 0 }).messageId;
  }
  /**
   * 移除loading
   */
  removeBasicMessage() {
    this.message.remove(this.messageId);
    this.messageId = null;
  }
  /**
  * 全局展示操作反馈信息
  * @param type 其他提示类型 success:成功 error:失败 warning:警告
  */
  createMessage(type: any, str: any): void {
    this.message.create(type, str);
  }

  /**
   * Dict类型转化文字
   * @returns
   */
  dictTextFilter(typeVal: String, arr: any) {
    let tmpObj: any = {};
    if (arr && arr.length) {
      tmpObj = arr.find((item: any) => item.content == typeVal);
    }

    return tmpObj?.name || '-';
  }

  // 订单来源平台change
  orderSourceChange(arrs: any) {
    this.queryForm.sourcePlatform = arrs.join(',');
  }
}
